package sfeir.gwt.ergosoom.client.profile;

import sfeir.gwt.ergosoom.client.ClientApi;
import sfeir.gwt.ergosoom.client.ClientApiAsync;
import sfeir.gwt.ergosoom.client.Messages;
import sfeir.gwt.ergosoom.client.ClientApi.NotLoggedInException;
import sfeir.gwt.ergosoom.client.faq.FaqStackPanel;
import sfeir.gwt.ergosoom.client.model.Profile;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.EventListener;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

public class ViewProfileEntryPoint implements EntryPoint, AsyncCallback<Profile> {
    private Messages message = GWT.create(Messages.class);
    
    @Override
    public void onModuleLoad() {
        String email = getUsername();
        ClientApiAsync server = (ClientApiAsync) GWT.create(ClientApi.class);
        if (email == null)
            return;
// TODO           server.getUserProfile(this);
        else
            server.getProfile(email, this);
    }
    
    @Override
    public void onSuccess(Profile result) {
        RootPanel.get("content").getElement().setInnerText("");
        if (result != null) {
            if (isMobile())
                RootPanel.get("content").add(new ViewProfileMobile(result));
            else
                RootPanel.get("content").add(new ViewProfile(result));
        }
        else {
            RootPanel.get("content").add(new Label(message.profile_contact_not_exist()));
        }
    }
    
    private native boolean isMobile() /*-{
       var ua = navigator.userAgent.toLowerCase();
 
       if (ua && (ua.indexOf("iphone") != -1 || ua.indexOf("android") != -1 || ua.indexOf("mobile") != -1)) {
         return true;
       }
       return false;
    }-*/;

    @Override
    public void onFailure(Throwable caught) {
        RootPanel.get("content").getElement().setInnerText("");
        GWT.log("Error", caught);
        if (caught instanceof NotLoggedInException)
            RootPanel.get("content").add(new Label(message.error_must_logging()));
        else
            RootPanel.get("content").add(new Label(message.error(caught.getMessage())));
    }
    
    private native String getUsername() /*-{
    // Get a reference to the first customer in the JSON array from earlier
    return $wnd.username; 
  }-*/;
}
